﻿using ApiLib.Cloud.Models;
using ApiLib.Helpers;
using ApiLib.Models;
using ApiLib.Utils;
using Furion.Schedule;

namespace ApiLib.Cloud.Common;

/// <summary>
/// 心跳
/// </summary>
[PeriodMinutes(1)]
public class CloudHealthJob : IJob
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <param name="stoppingToken"></param>
    public Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
    {
        if (MyCloudConstants.Config == null)
        {
            return Task.CompletedTask;
        }

        if (MyCloudConstants.CloudType == CloudModalType.Service)
        {
            /*var response = HttpUtil.HttpGet<BaseResponse<string>>(MyCloudConstants.Url.Health);
            if (response is { code: 0 })
            {
                Log.Information<CloudHealthJob>($"心跳结果：{response.data}");
            }
            else
            {
                Log.Error<CloudHealthJob>($"心跳结果：{response?.msg ?? ""}");
            }*/
        }
        else
        {
            var httpClient = HttpUtil.Builder(false, false, true, 1);
            httpClient.Timeout = TimeSpan.FromSeconds(10);
            var serviceInfos = DbHelper.Db.Queryable<ServiceInfo>()
                .Where(info => info.Type == 0)
                .Where(info => info.Online == true || (info.Online == false && info.RetryCount < 3))
                .ToList();
            if (!serviceInfos.IsNullOrEmpty())
            {
                foreach (var serviceInfo in serviceInfos)
                {
                    /*if (!serviceInfo.NeedHeart() || !serviceInfo.Online && serviceInfo.RetryCount > 3)
                    {
                        continue;
                    }*/
                    // var response = HttpUtil.HttpGet<BaseResponse<string>>(serviceInfo.HealthUrl);

                    var message = HttpUtil.GetRequestMessage(HttpMethod.Get, serviceInfo.HealthUrl);
                    var response = httpClient.SendRequest<BaseResponse<string>>(message);
                    if (response is { code: 0 })
                    {
                        if (!serviceInfo.Online)
                        {
                            serviceInfo.AddOnlineLog();
                        }

                        serviceInfo.Online = true;
                        serviceInfo.RetryCount = 0;
                        serviceInfo.HealthTime = CommonUtil.LocalDateTime();
                    }
                    else
                    {
                        if (serviceInfo.Online)
                        {
                            serviceInfo.AddOfflineLog();
                        }

                        serviceInfo.Online = false;
                        serviceInfo.RetryCount += 1;
                        serviceInfo.HealthTime = CommonUtil.LocalDateTime();
                        WebUtil.LogExp($"服务离线：{serviceInfo.Name}，Host：${serviceInfo.Host}");
                    }
                }

                DbHelper.Db.Updateable(serviceInfos).ExecuteCommand();
                CloudUtil.GetServiceInfo(true);

                /*DbHelper.Db.Updateable(serviceInfos)
                    .UpdateColumns(info => new { info.Online, info.HealthTime })
                    .ExecuteCommand();*/
            }
            else
            {
                if (DateTime.Now.Minute % 3 == 0)
                {
                    CloudUtil.GetServiceInfo(true);
                }
            }
        }

        return Task.CompletedTask;
    }
}